package com.siyuanren.gcocp.interceptor.wx;

import com.siyuanren.gcocp.common.config.PublicConfig;
import com.siyuanren.gcocp.consts.GcocpConsts;
import com.siyuanren.gcocp.consts.RedisConsts;
import com.siyuanren.gcocp.exception.WxException;
import com.siyuanren.gcocp.facade.JedisFacade;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author guwr
 */
@Slf4j
@Component
public class WxLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisFacade jedisFacade;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("interceptor url=" + request.getRequestURL().toString());
        if (PublicConfig.IS_DEV_STATUS) {
            return true;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            log.warn("cookies is null");
            throw WxException.NOT_LOGIN_ERROR;
        }
        String tokenVal = getTokenVal(cookies);

        if (StringUtils.isBlank(tokenVal)) {
            log.warn("tokenVal is null");
            throw WxException.NOT_LOGIN_ERROR;
        } else {
            log.info(tokenVal);
        }
        String tokenKey = String.format(RedisConsts.TOKEN_PREFIX, tokenVal);
        boolean exist = jedisFacade.exists(tokenKey);
        if (!exist) {
            log.warn("缓存中找不到token信息");
            throw WxException.NOT_LOGIN_ERROR;
        } {
            log.info(tokenKey + " is normal user");
        }
        request.setAttribute("token", tokenKey);
        // 重新设置过期时间为两小时
        jedisFacade.expire(tokenKey, GcocpConsts.LOGIN_TOKEN_TIME_OUT);
        return true;
    }

    /**
     * 获取cookie值
     */
    private String getTokenVal(Cookie[] cookies) {
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (Objects.equals(name, RedisConsts.TOKEN)) {
                return cookie.getValue();
            }
        }
        return StringUtils.EMPTY;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
